package fr.epsi.spring1.dao.utils;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.PoolingDataSource;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.log4j.Logger;

public class DatabaseManager {

	private final static Logger logger = Logger.getLogger(DatabaseManager.class);

	private DataSource ds = null;
	private GenericObjectPool connectionPool;

	private static DatabaseManager singleton;
	
	private DatabaseManager() {
		init();
	}
	
	private void init() {
		logger.info("Initialisation du pool de connexion");
		
		try {
			logger.info("Chargement du driver");
			Class.forName("org.hsqldb.jdbcDriver");
		} catch (ClassNotFoundException e) {
			logger.error("Impossible de charger le driver:" + e.getMessage());
			return;
		}

		connectionPool = new GenericObjectPool();
		connectionPool.setMaxActive(10);
		ConnectionFactory cf = new DriverManagerConnectionFactory(
				"jdbc:hsqldb:hsql://localhost:9003",
				"sa",
				"");
		PoolableConnectionFactory pcf = new PoolableConnectionFactory(cf, connectionPool,null, null, false, false);
		ds = new PoolingDataSource(connectionPool);
		logger.info("Fin initialisation du pool de connexion");
	}

    public void printStatus() {
        System.out.println("Max   : " + connectionPool.getMaxActive() + "; " + "Active: " + connectionPool.getNumActive());
    }
    
    public Connection getConnection() throws SQLException{
    	return ds.getConnection();
    }
    
    public static DatabaseManager getInstance() {
    	if (singleton == null) {
    		singleton = new DatabaseManager();
    	}
    	return singleton;
    }

}
